<script lang="ts" setup>
import { reactive, ref, watch } from "vue"
import { Search, Finished, Refresh } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"
import { getOrderListApi, addOrderListApi } from "@/api/capture-jd/index"
import { type FormInstance } from "element-plus"
import { formatDateTime } from "@/utils/index"
import { useUserStore } from "@/store/modules/user"
import { ElMessage } from "element-plus"
import { shortcuts } from "@/utils/dateSet"

const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
defineOptions({
  name: "CaptureListJd"
})
// #region 查
const defaultTime1: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 0)]
const searchFormRef = ref<FormInstance | null>(null)
const userStore = useUserStore()

// 搜索内容
const searchData = reactive<any>({
  time: "",
  id: "",
  status: ""
})
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  if (paginationData.currentPage === 1) {
    getTableData()
    console.log("重置")
  }
  paginationData.currentPage = 1
}
const handleSearch = () => {
  if (paginationData.currentPage === 1) {
    getTableData()
    console.log("查询")
  }
  paginationData.currentPage = 1
}
// #endregion
// #region 套餐
import { getComboDataApi } from "@/api/combo-jd"
const comboList = ref<any>([])
const tableData = ref<any>([])

// 获取 combo 数据
const getComboData = async () => {
  try {
    const res = await getComboDataApi({
      page: 1,
      size: 10000,
      type: "jd",
      userId: userStore.usernameID
    })
    comboList.value = res.data.list || []
    console.log(comboList.value, "查看京东套餐")
  } catch (error) {
    console.error("获取 combo 数据失败:", error)
  }
}

// 获取订单数据
const getTableData = async () => {
  try {
    // 确保 combo 数据已加载
    if (comboList.value.length === 0) {
      await getComboData()
    }

    // 将 comboList 转为 Map 提升查找效率
    const comboMap = new Map<string, string>(comboList.value.map((combo: any) => [combo.code, combo.systemId]))

    const res = await getOrderListApi({
      start: searchData.time[0] ? new Date(searchData.time[0]).getTime() : "",
      end: searchData.time[1] ? new Date(searchData.time[1]).getTime() : "",
      id: searchData.id || "",
      status: searchData.status || "",
      page: paginationData.currentPage,
      size: paginationData.pageSize,
      userId: userStore.usernameID
    })

    paginationData.total = res.data.total || 0
    tableData.value = (res.data.orderList || []).map((item: any) => {
      // 使用 Map 替代嵌套循环
      const systemId = comboMap.get(item.goods_id)
      if (systemId) {
        item.systemId = systemId
      }
      return item
    })

    console.log(res, "获取京东所有订单")
  } catch (error) {
    console.error("获取订单数据失败:", error)
  }
}

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
// #endregion

// #region 查看详情
const formData = reactive<any>({ data: {} })
const seeState = ref<string>("")
const dialogVisible = ref<boolean>(false)
const handleSeeInfo = (row: any) => {
  seeState.value = "see"
  rowData(row, false)
  console.log(row, "查看详情")
}
// row通用
const rowData = async (row: any, PL: boolean) => {
  currentUpdateId.value = row.id
  formData.data = row
  formData.data.id = row.id //订单ID
  formData.data.create_date = row.create_date //订单创建时间
  formData.data.goods_id = row.goods_id //商品编码
  formData.data.card_name = row.card_name //用户姓名
  formData.data.card_id = row.card_id //身份证号
  formData.data.consignee = row.consignee //收货人
  formData.data.name = row.name //收货人姓名
  formData.data.phone = row.phone //收货人联系电话
  formData.data.address = row.address //收货人联系地址
  formData.data.province_name = row.province_name //收货人省份名称
  formData.data.city_name = row.city_name //城市名称
  formData.data.county_name = row.county_name //区县名称
  formData.data.town_name = row.town_name //乡镇名称
  formData.data.ispType = row.ispType //运营商类型
  if (!PL) {
    // await getInfoMation(row)
    dialogVisible.value = true
    // dataArr.value.push(formData.data)
  } else {
    dataArr.value.push(row)
    console.log(row.id, 10923)
  }
  // loading.value = true
}
// #endregion

// #region 批量提交
const dataArr = ref<any>([])
const tableRef = ref<any>(null)
// 批量选择
const handleSelectionChange = (val: any) => {
  dataArr.value = []
  if (val.length) {
    val.forEach((item: any) => {
      if (!item.id) {
        tableRef.value?.clearSelection()
        return
      }
      rowData(item, true)
    })
  }
}
//  订单上传接口
const pushJd = async (data: any) => {
  // console.log(dataArr.value, "11111")
  // console.log(data, "22222")
  await addOrderListApi(data).then((res: any) => {
    // console.log(res, 1923)
    if (res.code == 200) {
      ElMessage.info(res.data)
      // console.log("请求通过", 8888888)
      dataArr.value = []
      tableRef.value?.clearSelection()
      getTableData()
    }
  })
}
const addItems = async () => {
  if (dataArr.value.length) pushJd(dataArr.value)
  console.log("批量提交")
}

// #endregion

//  #region 清除规则报错信息
const formRef = ref<FormInstance | null>(null)
const currentUpdateId = ref<undefined | string>(undefined)
const clearValidate = () => {
  formRef.value?.clearValidate()
}
const resetForm = () => {
  currentUpdateId.value = undefined
  seeState.value = ""
  dataArr.value = []
  clearValidate()
}
// #endregion

// #region 修改
const handleUpdate = (row: any) => {
  seeState.value = "update"
  rowData(row, false)
  console.log(row, "修改信息")
}
const handleCreate = () => {
  if (switchValue.value) {
    formData.data.systemId = ""
  } else {
    formData.data.heId = ""
  }
  // console.log("提交", formData.data)
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      dialogVisible.value = false
      addOrderListApi([formData.data]).then((res: any) => {
        // console.log(res, 1923)
        ElMessage.info(res.data)
        if (res.code == 200) {
          // console.log("请求通过", 8888888)
          dataArr.value = []
          tableRef.value?.clearSelection()
          getTableData()
        }
      })
    } else {
      return false
    }
  })
}
//#endregion
/**系统套餐 */
import { getComboDataApi10 } from "@/api/combo"
const comboListSys = ref<any>([])
const loading = ref<boolean>(false)
const getTableData1 = () => {
  loading.value = true
  getComboDataApi10({
    team: userStore.teamName,
    state: "true"
  })
    .then((res: any) => {
      comboListSys.value = res.data
    })
    .catch(() => {
      comboListSys.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
getTableData1()
/**加密 */
const toHideString = (val: any, len: any) => {
  if (val.length == 2) {
    return `${val.substring(0, len)}******${val.substring(val.length)}`
  } else {
    return `${val.substring(0, len)}******${val.substring(val.length - len)}`
  }
}

//合集套餐
import { getCompailationDataApi } from "@/api/combo"
const switchValue = ref(false)
const comboHJList = ref<any>([])
const getComboHjList = () => {
  getCompailationDataApi({
    page: 1,
    size: 1000,
    team: userStore.teamName
  })
    .then((res: any) => {
      comboHJList.value = res.data.list
    })
    .catch(() => {
      comboHJList.value = []
    })
    .finally(() => {})
}
getComboHjList()
const changeComboType = () => {
  formData.data.systemId = ""
  formData.data.heId = ""
}
</script>
<template>
  <div class="app-container">
    <el-card shadow="never" class="search-wrapper" v-loading="loading">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="id" label="订单ID">
          <el-input v-model.trim="searchData.id" clearable placeholder="请输入" style="width: 240px" />
        </el-form-item>
        <el-form-item prop="time" label="订单日期">
          <el-date-picker
            v-model="searchData.time"
            type="datetimerange"
            range-separator="到"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :shortcuts="shortcuts"
            :default-time="defaultTime1"
          />
        </el-form-item>
        <el-form-item prop="status" label="提交状态">
          <el-select v-model="searchData.status" clearable placeholder="请选择" style="width: 200px">
            <el-option label="未提交" value="0" />
            <el-option label="已提交" value="1" />
            <el-option label="提交失败" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      <el-button type="primary" :icon="Finished" @click="addItems">批量提交</el-button>
      <p style="color: red">
        套餐可选范围：套餐管理模块_产品列表/套餐合集（需要选择合集请点击切换为合集按钮）页面的套餐
      </p>
    </el-card>
    <el-card shadow="never">
      <div class="table-wrapper">
        <el-table v-loading="loading" :data="tableData" @selection-change="handleSelectionChange" ref="tableRef">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column prop="id" label="订单ID" align="center" />
          <el-table-column label="订单创建时间" width="100" align="center">
            <template #default="scope">
              {{ formatDateTime(scope.row.create_date) }}
            </template>
          </el-table-column>
          <el-table-column prop="goods_id" label="商品编码" align="center" />
          <el-table-column align="center" width="260">
            <template #header>
              <span>系统套餐</span>
              <p><el-switch v-model="switchValue" @change="changeComboType" />切换为合集</p>
            </template>
            <template #default="scope">
              <el-select v-if="!switchValue" v-model="scope.row.systemId" clearable filterable>
                <el-option v-for="item in comboListSys" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
              <el-select v-else v-model="scope.row.heId" clearable filterable>
                <el-option v-for="item in comboHJList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </template>
          </el-table-column>

          <el-table-column prop="status" label="状态" align="center">
            <template #default="scope">
              <div>
                <el-text v-if="scope.row.status == '1'" class="mx-1" type="primary">已提交</el-text>
                <el-text v-if="scope.row.status == '0'" class="mx-1" type="danger">未提交</el-text>
                <el-text v-if="scope.row.status == '2'" class="mx-1" type="danger">提交失败</el-text>
                <div class="text-ellipsis" v-if="scope.row.result" style="font-size: 12px">
                  <el-tooltip placement="top">
                    <template #content> {{ scope.row.result }} </template>
                    <span style="cursor: pointer">({{ scope.row.result }})</span>
                  </el-tooltip>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="card_name" label="用户姓名" align="center" />
          <!-- <el-table-column prop="card_id" label="身份证号" align="center" /> -->
          <el-table-column prop="card_id" label="身份证号" align="center">
            <template #default="scope">
              {{ toHideString(scope.row.card_id, 6) }}
            </template>
          </el-table-column>
          <!-- <el-table-column prop="consignee" label="收货人" align="center" /> -->
          <el-table-column prop="name" label="收货人姓名" align="center" />
          <!-- <el-table-column prop="phone" label="收货人联系电话" align="center" /> -->
          <el-table-column prop="phone" label="收货人联系电话" align="center">
            <template #default="scope">
              {{ toHideString(scope.row.phone, 4) }}
            </template>
          </el-table-column>
          <el-table-column prop="" label="收货人省份名称" align="center">
            <template #default="scope">
              <el-text class="mx-1" v-if="scope.row.province_name.indexOf('市') != -1"
                >{{ scope.row.province_name }}
              </el-text>
              <el-text class="mx-1" v-else> {{ scope.row.province_name }}</el-text>
              <!-- {{ scope.row.province_name }} -->
            </template>
          </el-table-column>
          <el-table-column prop="city_name" label="城市名称" align="center" />
          <el-table-column prop="county_name" label="区县名称" align="center" />
          <el-table-column prop="town_name" label="乡镇名称" align="center" />
          <!-- <el-table-column prop="address" label="收货人联系地址" align="center" /> -->
          <el-table-column label="收货地址" align="center" show-overflow-tooltip>
            <template #default="scope">
              {{ toHideString(scope.row.address, 2) }}
            </template>
          </el-table-column>
          <el-table-column prop="ispType" label="运营商类型" align="center">
            <template #default="scope">
              <span v-if="scope.row.ispType == 1">移动</span>
              <span v-else-if="scope.row.ispType == 2">联通</span>
              <span v-else-if="scope.row.ispType == 3">电信</span>
              <span v-else-if="scope.row.ispType == 4">京东通信</span>
              <span v-else>中国广电</span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="100" align="center">
            <template #default="scope">
              <el-button
                type="primary"
                v-if="scope.row.status !== 1"
                text
                bg
                size="small"
                @click="handleUpdate(scope.row)"
                >修改信息</el-button
              ><br /><br />
              <el-button type="primary" text bg size="small" @click="handleSeeInfo(scope.row)">查看详情</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 新增/修改 -->
    <el-dialog
      v-model="dialogVisible"
      :title="seeState === 'see' ? '查看详情' : '修改信息'"
      @close="resetForm"
      width="60%"
    >
      <el-form ref="formRef" :model="formData.data" label-width="100px" label-position="left">
        <el-row :gutter="20">
          <el-col :span="12">
            <div>
              <h4>身份证信息:</h4>
              <div style="padding-left: 20px">
                <el-form-item prop="id" label="订单ID" v-if="seeState == 'see'">
                  <el-input v-model="formData.data.id" placeholder="请输入订单编号" :disabled="seeState === 'see'" />
                </el-form-item>
                <el-form-item prop="card_name" label="用户姓名">
                  <el-input
                    v-model="formData.data.card_name"
                    placeholder="请输入"
                    type="textarea"
                    :disabled="seeState === 'see'"
                  />
                </el-form-item>
                <el-form-item prop="card_id" label="身份证号">
                  <el-input
                    v-model="formData.data.card_id"
                    placeholder="请输入"
                    type="textarea"
                    :disabled="seeState === 'see'"
                  />
                </el-form-item>
                <!--  -->
                <el-form-item label="系统套餐">
                  <el-select v-if="!switchValue" v-model="formData.data.systemId" clearable filterable>
                    <el-option v-for="item in comboListSys" :key="item.id" :label="item.name" :value="item.id" />
                  </el-select>
                  <el-select v-else v-model="formData.data.heId" clearable filterable>
                    <el-option v-for="item in comboHJList" :key="item.id" :label="item.name" :value="item.id" />
                  </el-select>
                  <span style="margin-left: 10px"
                    >切换为合集套餐 <el-switch v-model="switchValue" @change="changeComboType"
                  /></span>
                </el-form-item>
                <!--  -->
                <el-form-item prop="remark" label="备注">
                  <el-input
                    v-model="formData.data.remark"
                    placeholder="请输入"
                    type="textarea"
                    :disabled="seeState === 'see'"
                  />
                </el-form-item>
              </div>
            </div>
          </el-col>
          <el-col :span="12">
            <div>
              <h4>收件信息:</h4>
              <div style="padding-left: 20px">
                <!-- <el-form-item prop="consignee" label="收货人">
                  <el-input v-model="formData.data.consignee" placeholder="请输入" :disabled="seeState === 'see'" />
                </el-form-item> -->
                <el-form-item prop="name" label="收货人姓名">
                  <el-input v-model="formData.data.name" placeholder="请输入" :disabled="seeState === 'see'" />
                </el-form-item>
                <el-form-item prop="province_name" label="省份名称">
                  <el-input v-model="formData.data.province_name" placeholder="请输入" :disabled="seeState === 'see'" />
                </el-form-item>
                <el-form-item prop="city_name" label="城市名称">
                  <el-input v-model="formData.data.city_name" placeholder="请输入" :disabled="seeState === 'see'" />
                </el-form-item>
                <el-form-item prop="county_name" label="区县名称">
                  <el-input v-model="formData.data.county_name" placeholder="请输入" :disabled="seeState === 'see'" />
                </el-form-item>
                <el-form-item prop="town_name" label="乡镇名称">
                  <el-input v-model="formData.data.town_name" placeholder="请输入" :disabled="seeState === 'see'" />
                </el-form-item>
                <el-form-item prop="phone" label="联系电话">
                  <el-input v-model="formData.data.phone" placeholder="请输入" :disabled="seeState === 'see'" />
                </el-form-item>
                <el-form-item prop="address" label="联系地址">
                  <el-input
                    v-model="formData.data.address"
                    placeholder="请输入"
                    type="textarea"
                    :disabled="seeState === 'see'"
                  />
                </el-form-item>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate" v-if="seeState !== 'see'">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  .btn {
    width: 100%;
    height: 100%;
    display: flex;
  }
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
:deep(.el-upload-list__item .el-icon--close-tip) {
  top: 20px;
  left: 10px;
  right: 0;
}
.doing {
  color: #b88230;
}
.error {
  color: red;
}
.success {
  color: #67c23a;
}
.again {
  color: #c45656;
}
:deep(.el-popper) {
  max-width: 50% !important;
}
.date-box {
  width: 340px !important;
}
.text-ellipsis {
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  -webkit-line-clamp: 3;
  display: -webkit-box;
  -webkit-box-orient: vertical;
}
</style>
<style>
.el-popper.is-customized {
  /* Set padding to ensure the height is 32px */
  padding: 6px 12px;
  background: linear-gradient(90deg, rgb(159, 229, 151), rgb(204, 229, 129));
}

.el-popper.is-customized .el-popper__arrow::before {
  background: linear-gradient(45deg, #b2e68d, #bce689);
  right: 0;
}
.pbox {
  line-height: 2em;
}
.flag {
  display: inline-block;
  width: 10px;
  height: 10px;
  border-radius: 50%;
}
.red {
  background: red;
}
.yellow {
  background: rgb(255, 220, 0);
}
.green {
  background: green;
}
.blue {
  background: blue;
}
.purple {
  background: purple;
}
.goodInfo {
  text-align: left;
}
.esp {
  width: 180px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  cursor: pointer;
}
</style>
